import {InputNumber, Button, Input, Modal, Popconfirm, Table, Select, Form,} from "antd";
import React from "react";
import API from "../../api/api";
import UserForm from './UserForm';
import UpdateUserForm from "./UpdateUserForm";
import {config} from '../../util/config'
let Option = Select;

export default class User extends React.Component{
    constructor(props) {
        super(props);
        // store.subscribe(() => {this.setState({visible:store.getState().visible})})
        this.state = {
            bindObj:"user",
            status:true,
            data : [],
            insertVisible:false,
            updateVisible:false,
            buttonVisible:false,
            selectedRowKeys: [], // Check here to configure the default column
            loading: false,
            visible:false
        };
    }

    data=[];

    status = null;

    text = config.is_delete;

    columns = [];

    columns1 = [
        {
            title: '用户',
            dataIndex: 'name',
            width:200,
            ellipsis:true,
            render: (text) => (
                <a >
                    {text}
                </a>
            ),
        },
        {
            title:"工号",
            width:160,
            ellipsis:true,
            dataIndex:"userWorkNum"
        },
        {
            title:"部门",
            width:160,
            ellipsis:true,
            dataIndex:"department"
        },
        // {
        //     title: '建立人',
        //     dataIndex:"createUser",
        //     ellipsis:true,
        //     key: 'Options',
        //     width:200
        // },
        // {
        //     title: '建立时间',
        //     dataIndex:"createTime",
        //     ellipsis:true,
        //     key: 'Options',
        //     width:200
        // },
        {
            title:"修改人",
            width:210,
            ellipsis:true,
            dataIndex:"updateUser"
        },
        {
            title:"修改时间",
            width:210,
            ellipsis:true,
            dataIndex:"updateDate"
        },
        {
            title: '操作',
            width:150,
            ellipsis:true,
            key: 'Options',
            render: (text, record) => (
                <div>
                    <Button style={{marginRight:"0.5rem"}} type="primary" shape="round" size="middle" onClick={_=>{this.update(record)}}>
                        修改
                    </Button>
                    <Popconfirm placement="right" title={this.text} onConfirm={_=>{this.delete(record)}} okText="确定" cancelText="取消">
                        <Button type="primary" shape="round" style={{marginRight: "1rem", border: "0.1rem solid #ff7875"}} danger>
                        删除
                    </Button>
                    </Popconfirm>
                </div>
            ),
        },
    ];

    columns2 = [
        {
            title: '部门',
            dataIndex: 'name',
            width:200,
            render: (text, record) => (
                <a onClick={_=>{
                    alert("clicked:"+record.key)
                }}>
                    {text}
                </a>
            ),
        },
        {
            title:"部门编号",
            dataIndex:"no",
            width:200,
        },
        // {
        //     title: '建立人',
        //     dataIndex:"createUser",
        //     ellipsis:true,
        //     key: 'Options',
        //     width:200
        // },
        // {
        //     title: '建立时间',
        //     dataIndex:"createTime",
        //     ellipsis:true,
        //     key: 'Options',
        //     width:200
        // },
        {
            title:"修改人",
            width:200,
            ellipsis:true,
            dataIndex:"updateUser"
        },
        {
            title:"修改时间",
            width:200,
            ellipsis:true,
            dataIndex:"updateDate"
        },
        {
            title: '操作',
            key: 'Options',
            width:180,
            render: (text, record) => (
                <div>
                    <Button style={{marginRight:"0.5rem"}} type="primary" shape="round" size="middle"   onClick={_=>{this.updateDept(record)}}>
                        修改
                    </Button>
                    <Popconfirm placement="right" title={this.text} onConfirm={_=>{this.deleteDept(record)}} okText="确定" cancelText="取消">
                        <Button type="primary" shape="round" style={{marginRight: "1rem", border: "0.1rem solid #ff7875"}} danger>
                            删除
                        </Button>
                    </Popconfirm>
                </div>
            ),
        },
    ];

    result=(result)=>{
        this.status = result;
    }

    getUsers=()=>{
        this.data = API.getUserBind();
    }

    getDepts=()=>{
        this.data = API.getDeptBind();
    }

    insert = () => {
        this.setState({
            insertVisible:true,
            status:false
        });
    }

    update = (record) => {
        sessionStorage.setItem("userId",record.key);
        this.setState({
            updateVisible:true,
            status:false
        });
    }

    updateDept = (record) => {
        sessionStorage.setItem("deptId",record.key);
        this.setState({
            updateVisible:true,
            status:false
        });
    }

    delete = (record) => {
        if(API.deleteUserBind([record.key])){
            this.setState({
                status:true
            })
        }else{
            this.setState({
                status:false
            })
        }
    }

    deleteDept = (record) => {
        if(API.deleteDeptBind([record.key])){
            this.setState({
                status:true
            })
        }else{
            this.setState({
                status:false
            })
        }
    }

    cancel = () => {
        // ajax request after empty completing
        this.setState({
            selectedRowKeys: [],
            loading: false,
            status:false
        });
    };

    deleteSelect=()=>{
        if(API.deleteUserBind(this.state.selectedRowKeys)){
            this.setState({
                status: true
            });
        }else {
            this.setState({
                status: false
            });
        }
    }

    deleteDeptSelect=()=>{
        if(API.deleteDeptBind(this.state.selectedRowKeys)){
            this.setState({
                status: true
            });
        }else {
            this.setState({
                status: false
            });
        }
    }

    onSelectChange = selectedRowKeys => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.setState({
            selectedRowKeys:selectedRowKeys,
            status:false
        });
    };

    handleCancel = () => {
        if(this.status=="ok"){
            this.status=false;
            this.setState({
                insertVisible: false,
                updateVisible:false,
                status:true
            });
        }else{
            this.setState({
                insertVisible: false,
                updateVisible:false,
                status:false
            });
        }
    };

    changeList = (item) => {
        this.setState({
            bindObj:item,
            status:true
        })
    }

    users=null

    depts=null

    onSearch = (values)=>{
        if(this.state.bindObj=="user"){
            if(this.users==null){
                this.users = JSON.parse(sessionStorage.getItem("usersBind"))
            }
            this.data = this.users.filter(item => (item.userWorkNum&&item.userWorkNum.indexOf(values)!=-1) || (item.name&&item.name.indexOf(values)!=-1) || (item.department&&item.department.indexOf(values)!=-1));
        }else if(this.state.bindObj=="dept"){
            if(this.depts==null){
                this.depts = JSON.parse(sessionStorage.getItem("deptsBind"))
            }
            this.data = this.depts.filter(item => (item.no&&item.no.indexOf(values)!=-1) || (item.name&&item.name.indexOf(values)!=-1));
        }
        this.setState({status:false})
    }
    title = "用户";
    render() {
        if(this.state.status){
            if(this.state.bindObj=="user"){
                this.getUsers();
                this.title = "用户"
            }else {
                this.getDepts();
                this.title = "部门"
            }
        }

        if(this.state.bindObj=="user"){
            this.columns = this.columns1
        }else this.columns = this.columns2

        const { loading, selectedRowKeys } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const hasSelected = selectedRowKeys.length > 0;
        return (
            <>
                <div style={{marginBottom:"1rem" }}>
                    <Button type="primary" onClick={this.insert} style={{marginRight:"0.5rem"}}>
                        添加
                    </Button>
                    <Button type="danger" onClick={this.state.bindObj=="user"?this.deleteSelect:this.deleteDeptSelect } disabled={!hasSelected} style={{marginRight:"0.5rem"}}>
                        删除选中
                    </Button>
                    <Button type="primary" onClick={this.cancel} disabled={!hasSelected}>
                        取消
                    </Button>
                    <Form
                        style={{display:"inline",marginLeft:"1rem"}}
                        layout={"inline"}
                    >
                        <Form.Item
                            name="roleType"
                            label="赋权对象"
                            style={{display:"inline"}}
                        >
                            <Select
                                // placeholder="Select a option and change input text above"
                                onChange={this.changeList}
                                style={{width:'6rem'}}
                                defaultValue={"user"}
                            >
                                <Option value="user">用户</Option>
                                <Option value="dept">部门</Option>
                            </Select>
                        </Form.Item>
                        <Form.Item
                            name="keys"
                            label={this.title+"查询"}
                            style={{display:"inline"}}
                        >
                            <Input.Search style={{ width: 200 }} allowClear enterButton onSearch={(item)=>{this.onSearch(item)}}/>
                        </Form.Item>
                    </Form>
                </div>
                <Table className="decorate" size={"middle"} rowSelection={rowSelection} columns={this.columns} dataSource={this.data} scroll={{ x:60}}/>
                <Modal
                    width={1000}
                    mask={false}
                    destroyOnClose
                    visible={this.state.insertVisible || this.state.updateVisible}
                    title={"角色管理"}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    footer={[
                        <Button key="back" onClick={this.handleCancel}>退出</Button>
                    ]}
                >
                    {this.state.insertVisible ? <UserForm bindObj={this.state.bindObj} result={this.result}/> : null}
                    {this.state.updateVisible ? <UpdateUserForm bindObj={this.state.bindObj} result={this.result}/> : null}
                </Modal>
            </>
        );
    }
}
